//
//  EarningsVC.swift
//  LeTu
//
//  Created by gy on 2023/11/24.
//

import UIKit

class EarningsVC: BaseViewController {

    private var viewModel = EarningsVM()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        title = "收益".localized
        rightBtn.setTitle("收益说明".localized, for: .normal)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem()
        earningsTableView.headerBeginRefreshing()
    }
    private func getRecords(isLoad: Bool) {
        
        if isLoad == false {
            earningsTableView.footerResetNoMoreData()
        }
        
        viewModel.getIncomeRecords(isLoad: isLoad) { [weak self] dialog in
            
            guard let strongSelf = self else { return }
            
            DispatchQueue.main.async {
                
                if isLoad {
                    strongSelf.earningsTableView.footerEndRefreshing()
                } else {
                    strongSelf.earningsTableView.headerEndRefreshing()
                }
                
                if !(dialog.code == 200 || dialog.code != 401)  {
                    //strongSelf.showMessage(message: dialog.message)
                    strongSelf.viewModel.sourceArr = []
                }
                
                if let count = dialog.data as? Int, count == 0 || count < strongSelf.viewModel.pageSize {
                    strongSelf.earningsTableView.footerEndRefreshingWithNoMoreData()
                }
                strongSelf.earningsTableView.reloadData()
                
            }
            
        }
        
        viewModel.getBalance { [weak self] dialog in
            guard let strongSelf = self else { return }
            strongSelf.earningsTableView.reloadData()
        }
        
    }
    // MARK: - UIButtonAction
    @objc func rightBarButtonItemAction() {
        show(AppWebViewController(url: "https://doc.jc-tour.net/revenueStatement.html", isShowNav: true), sender: nil)
    }
    
    // MARK: - configUI
    func configUI() {
        
        navIsHidden = false
        
        rightBtn.titleLabel?.font = kSetPingFangRegular(15)
        rightBtn.setTitleColor(.app_themeColor, for: .normal)
        rightBtn.addTarget(self, action: #selector(rightBarButtonItemAction), for: .touchUpInside)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        view.addSubview(earningsTableView)
        
        earningsTableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        earningsTableView.delegate = self
        earningsTableView.dataSource = self
        earningsTableView.register(cellClass: BaseEmptyTableViewCell.self)
        earningsTableView.register(cellClass: EarningsInfoTableViewCell.self)
        earningsTableView.register(cellClass: EarningsDetailsTableViewCell.self)
        earningsTableView.register(cellClass: EarningsAdTableViewCell.self)

        earningsTableView.addRefreshHeaderCallback { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.getRecords(isLoad: false)
        }
        earningsTableView.addRefreshFooterCallback { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.getRecords(isLoad: true)
        }
        
    }
    private var earningsTableView: UITableView = {
        let earningsTableView = UITableView()
        earningsTableView.showsVerticalScrollIndicator = false
        earningsTableView.tableFooterView = UIView()
        return earningsTableView
    }()
    private var rightBtn = UIButton()

}

extension EarningsVC: TransferEventReceivable {
    
    enum TransferEvent: TransferEventType {
    case toWithdraw
    }
    
    func receive(event: TransferEventType) {
        
        switch event {
        case EarningsVC.TransferEvent.toWithdraw:
            guard kUserManager.isLogin else {
                kUserManager.toLogin()
                return
            }
            show(WithdrawVC(balance: "\(viewModel.totalBalance)"), sender: nil)
        default:
            break
        }
        
    }
    
}

extension EarningsVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 1 ? 60:0.01
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 {
            let headerView = EarningsHeaderView()
            return headerView
        }
        return UIView()
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return section == 0 ? 10:0.01
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
            let footerView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: tableView.sectionFooterHeight))
            footerView.backgroundColor = .app_viewBackgroundColor
            return footerView
        }
        return UIView()
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let topHeight = EarningsInfoTableViewCell.getCellHeight()
        if indexPath.section == 0 {
            return topHeight
        } else if indexPath.section == 2 {
            return EarningsAdTableViewCell.getEarningsAdCellHeight().height
        }
        guard viewModel.sourceArr.count > 0 else {
            return tableView.height-topHeight-tableView.sectionHeaderHeight-tableView.sectionFooterHeight-Size.tabBarHeight
        }
        return EarningsDetailsTableViewCell.getCellHeight()
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        return viewModel.sourceArr.count == 0 ? 1:viewModel.sourceArr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(EarningsInfoTableViewCell.self, indexPath: indexPath)
            cell.updateInfo(balance: viewModel.totalBalance)
            return cell
        } else if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(EarningsAdTableViewCell.self, indexPath: indexPath)
            //cell.setAdView(adView!)
            return cell
        }
        if viewModel.sourceArr.count == 0 {
            let cell = tableView.dequeueReusableCell(BaseEmptyTableViewCell.self, indexPath: indexPath)
            cell.setInfo(iconName: "nodata", title: "暂无数据".localized)
            return cell
        }
        let cell = tableView.dequeueReusableCell(EarningsDetailsTableViewCell.self, indexPath: indexPath)
        cell.setRecordModel(viewModel.sourceArr[indexPath.row])
        return cell
    }
        
}

